package services

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"

	"QWenVL/models"
)

func CallQwenVLAPI(headers map[string]string, requestBody *models.RequestBody) (string, error) {
	client := &http.Client{}

	jsonBody, err := json.Marshal(requestBody)
	if err != nil {
		return "", err
	}

	// 发送请求
	req, err := http.NewRequest("POST", "https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation", bytes.NewBuffer(jsonBody))
	if err != nil {
		return "", err
	}
	for key, header := range headers {
		req.Header.Set(key, header)
	}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// 读取响应内容
	responseBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	// 返回响应内容
	return string(responseBody), nil
}

func UploadImgDirParse(file string) (string, error) {
	url := "http://150.158.180.15/eruploads/"

	// 打开文件
	f, err := os.Open(file)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	// 创建buffer
	var buffer bytes.Buffer
	//通过包multipart实现了MIME的multipart解析
	writer := multipart.NewWriter(&buffer)
	part, err := writer.CreateFormFile("file", file)
	if err != nil {
		panic(err)
	}
	// 拷贝文件内容到新建FormFile中
	_, err = io.Copy(part, f)
	if err != nil {
		panic(err)
	}
	err = writer.Close()
	if err != nil {
		panic(err)
	}
	// 创建HTTP POST请求
	req, err := http.NewRequest("POST", url, &buffer)
	if err != nil {
		panic(err)
	}
	// 设置头信息为：multipart/form-data
	req.Header.Add("Content-Type", writer.FormDataContentType())
	// 实例化一个http客户端对象
	client := &http.Client{}
	// 发送请求
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	resBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(resBody), nil

}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		// 确保我们使用POST方法
		r.ParseMultipartForm(32 << 20) // 限制内存中的最大文件大小为32MB

		// 从表单中获取文件
		file, handler, err := r.FormFile("file")
		if err != nil {
			http.Error(w, "File upload error: "+err.Error(), http.StatusBadRequest)
			return
		}
		defer file.Close()

		// 保存文件到服务器的文件系统
		filePath := filepath.Join("./uploads", handler.Filename)
		out, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			http.Error(w, "File saving error: "+err.Error(), http.StatusInternalServerError)
			return
		}
		defer out.Close()

		// 将文件内容复制到服务器上的新文件中
		_, err = io.Copy(out, file)
		if err != nil {
			http.Error(w, "File write error: "+err.Error(), http.StatusInternalServerError)
			return
		}

		// 返回成功响应
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("File uploaded successfully"))
	} else {
		// 如果不是POST请求，返回405 Method Not Allowed
		http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
	}
}
